package store.lunangangster.engine.impl.db;

import org.apache.ibatis.session.SqlSessionFactory;
import store.lunangangster.engine.ProcessEngineConfiguration;
import store.lunangangster.engine.impl.IdGenerator;
import store.lunangangster.engine.impl.db.cache.EntityCache;
import store.lunangangster.engine.impl.db.cache.EntityCacheSessionFactory;

public class DbSqlSessionFactory implements SessionFactory {

  protected ProcessEngineConfiguration processEngineConfiguration;
  protected SqlSessionFactory sqlSessionFactory;
  protected Statements statements;
  protected IdGenerator idGenerator;
  protected EntityCacheSessionFactory entityCacheSessionFactory;

  public static DbSqlSessionFactory newInstance(SqlSessionFactory sqlSessionFactory, Statements statements, IdGenerator idGenerator, ProcessEngineConfiguration processEngineConfiguration) {
    DbSqlSessionFactory dbSqlSessionFactory = new DbSqlSessionFactory();
    dbSqlSessionFactory.setSqlSessionFactory(sqlSessionFactory);
    dbSqlSessionFactory.setStatements(statements);
    dbSqlSessionFactory.setIdGenerator(idGenerator);
    dbSqlSessionFactory.setProcessEngineConfiguration(processEngineConfiguration);
    dbSqlSessionFactory.setEntityCacheSessionFactory(
        processEngineConfiguration.getEntityCacheSessionFactory());
    return dbSqlSessionFactory;
  }



  @Override
  public DbSqlSession openSession() {
    return openSession(false);
  }

  @Override
  public DbSqlSession openSession(boolean autoCommit) {
    DbSqlSession dbSqlSession = new DbSqlSession(this);
    dbSqlSession.sqlSession = sqlSessionFactory.openSession(autoCommit);
    dbSqlSession.autoCommit = autoCommit;
    return dbSqlSession;
  }

  public EntityCache getEntityCache() {
    return entityCacheSessionFactory.openSession();
  }

  public boolean isBatchInsert() {
    return true;
  }

  public ProcessEngineConfiguration getProcessEngineConfiguration() {
    return processEngineConfiguration;
  }

  public void setProcessEngineConfiguration(
      ProcessEngineConfiguration processEngineConfiguration) {
    this.processEngineConfiguration = processEngineConfiguration;
  }

  public SqlSessionFactory getSqlSessionFactory() {
    return sqlSessionFactory;
  }

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  public Statements getStatements() {
    return statements;
  }

  public void setStatements(Statements statements) {
    this.statements = statements;
  }

  public IdGenerator getIdGenerator() {
    return idGenerator;
  }

  public void setIdGenerator(IdGenerator idGenerator) {
    this.idGenerator = idGenerator;
  }

  public EntityCacheSessionFactory getEntityCacheSessionFactory() {
    return entityCacheSessionFactory;
  }

  public void setEntityCacheSessionFactory(
      EntityCacheSessionFactory entityCacheSessionFactory) {
    this.entityCacheSessionFactory = entityCacheSessionFactory;
  }
}
